package com.web.kdl.service.user;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.web.kdl.common.result.CommonResult;
import com.web.kdl.common.result.MessageConstants;
import com.web.kdl.common.result.ReturnCode;
import com.web.kdl.dao.user.UserDao;
import com.web.kdl.daoV2.auth.RoleDao;
import com.web.kdl.daoV2.auth.UserRoleDao;
import com.web.kdl.entity.auth.RoleInfo;
import com.web.kdl.entity.auth.UserRole;
import com.web.kdl.entity.user.UserInfo;
import com.web.kdl.pojo.Vo.UserVo;
import com.web.kdl.pojo.form.UserAddForm;
import com.web.kdl.pojo.form.UserForm;
import com.web.kdl.pojo.form.UserUpdateForm;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * @author zq
 * @date 2022/7/2 12:00
 */
@Service
public class UserServiceImpl implements UserService{
//  密码加密注入
    @Resource
    private PasswordEncoder passwordEncoder;
    @Autowired
    UserDao userDao;
    @Autowired
    RoleDao roleDao;
    @Autowired
    UserRoleDao userRoleDao;

    @Override
    @Transactional
    public Boolean addUser(UserAddForm form) {
//      正式注册
        UserInfo user = new UserInfo();
        user.setUsername(form.getUsername());
        user.setPassword(passwordEncoder.encode(form.getPassword()));
        user.setRole(form.getRole());
        user.setEmail(form.getEmail());
        int re1 = userDao.insert(user);
        UserRole userRole = new UserRole();
        userRole.setUserId(String.valueOf(user.getId()));
        RoleInfo role = roleDao.selectOne(new LambdaQueryWrapper<RoleInfo>().eq(RoleInfo::getRoleCode, form.getRole()));
        userRole.setRoleId(role.getId());
        int re2 = userRoleDao.insert(userRole);
        return re1 > 0 && re2 > 0;
    }

    @Override
    public UserInfo findByUsername(String username) {
        UserInfo user = userDao.findByUsername(username);
        if (ObjectUtils.isEmpty(user))
            return null;
        return user;
    }

    @Override
    public CommonResult login(UserForm form) {
        UserInfo user =findByUsername(form.getUsername());
        if (user==null) {
            return CommonResult.error(ReturnCode.FAIL.getCode(),MessageConstants.INVALID_CREDENTIALS);
        }
        // 3. 密码匹配
        if (!passwordEncoder.matches(form.getPassword(), user.getPassword())) {
            return CommonResult.error(ReturnCode.FAIL.getCode(),MessageConstants.INVALID_CREDENTIALS);
        }
        return CommonResult.success(MessageConstants.LOGIN_SUCCESS);
    }

    @Override
    public List<UserVo> getAllUser() {
        return userDao.getAllUser();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateUser(UserUpdateForm form) {
        UserInfo userInfo = userDao.selectById(form.getId());
        if (!userInfo.getRole().equals(form.getRole())) {
            // 获取新角色信息
            RoleInfo role = roleDao.selectOne(
                    new LambdaQueryWrapper<RoleInfo>()
                            .eq(RoleInfo::getRoleCode, form.getRole())
            );
            if (role == null) {
                // 角色不存在时抛出异常或返回错误
                throw new RuntimeException("角色不存在");
            }
            UserRole userRole = new UserRole();
            userRole.setRoleId(role.getId());
            // 更新 user_role 表
            userRoleDao.update(
                    userRole,
                    new LambdaQueryWrapper<UserRole>()
                            .eq(UserRole::getUserId, userInfo.getId())
            );
        }
        BeanUtils.copyProperties(form, userInfo);
        if (form.getPassword()!= null || !form.getPassword().isEmpty())
        userInfo.setPassword(passwordEncoder.encode(form.getPassword()));
        int i = userDao.updateById(userInfo);
        return i > 0;
    }

    @Override
    public Boolean resetPassword(UserInfo form) {
        int i = userDao.updateById(form);
        return i > 0;
    }

    @Override
    public int deleteByIds(List<String> userIds) {
        userRoleDao.delete(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, userIds));
        return userDao.deleteByIds(userIds);
    }

    @Override
    public List<String> listAuthorityById(String userId) {
        return userDao.listAuthorityById(userId);
    }
    
    @Override
    public Boolean updatePassword(String username, String password) {
        UserInfo user = userDao.findByUsername(username);
        if (user == null) {
            return false;
        }
        user.setPassword(passwordEncoder.encode(password));
        int i = userDao.updateById(user);
        return i > 0;
    }
}
